package main.handler;

import com.google.protobuf.GeneratedMessageV3;
import main.bean.Message;
import main.bean.Player;
import main.bean.Room;
import main.protobuf.Common;
import main.service.GameCache;
import main.service.IHandler;
import main.service.MessageId;
import main.utils.GameUtils;
import threadPool.thread.DisruptorExecutorPool;

/**
 * Created by JinMiao
 * 2019-08-02.
 */
public class JoinRoomHandler implements IHandler {
    @Override
    public void handler(Player player, Message msg, GameCache gameCache) throws Throwable {
        joinRoom(player,gameCache);
        msg.clear();
        msg.setActionId(MessageId.JoinRoom_S2C);
        Common.JoinRoomS2C.Builder builder = Common.JoinRoomS2C.newBuilder();
        builder.setPlayerId(player.getId());
        msg.setBody(builder.build());
        GameUtils.sendTo(msg,player);
    }


    public synchronized void joinRoom(Player player, GameCache gameCache){
        Room room = null;
        for (Room value : gameCache.playerRooms.values()) {
            if(value.getPlayers().size()==1)
            {
                continue;
            }
            if(room==null){
                room = value;
                continue;
            }
            if(room.getPlayers().size()>value.getPlayers().size()){
                room = value;
            }
        }
        if(room==null){
            room = new Room();
            room.setiMessageExecutor(gameCache.disruptorExecutorPool.getAutoDisruptorProcessor());
            DisruptorExecutorPool.scheduleWithFixedDelay(room,50);
        }
        gameCache.playerRooms.put(player.getId(),room);
        room.getPlayers().put(player.getId(),player);
    }

    @Override
    public short messageId() {
        return MessageId.JoinRoom_C2S;
    }

    @Override
    public  Class<? extends GeneratedMessageV3> initBodyClass() {
        return null;
    }

    @Override
    public String getExecuteName() {
        return null;
    }
}
